package cn.wilson.hrm;

import cn.wilson.hrm.doc.CourseDoc;
import cn.wilson.hrm.repository.CourseElasticsearchRepository;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.List;

/**
 *      es的工具
 */
@RunWith(SpringRunner.class)
@SpringBootTest(classes = EsServerApplication2050.class)
public class ESTest {

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    @Autowired
    private CourseElasticsearchRepository courseElasticsearchRepository;

    @Test
    public void testCreateIndex() {
        //创建索引
        elasticsearchTemplate.createIndex(CourseDoc.class);
        //做文档映射
        elasticsearchTemplate.putMapping(CourseDoc.class);
    }

    /**
     *      添加
     */
    @Test
    public void testAdd(){
        for (int i = 0; i <50; i++) {
            CourseDoc courseDoc = new CourseDoc();
            courseDoc.setId(i + 1L);
            //当偶数时我们设置的值不一样
            if (i %2 == 0){
                courseDoc.setName("mysql数据库精通");
                courseDoc.setIntro("mysql学不会就放弃吧");
                courseDoc.setCourseTypeId(i + 10086L);
            }else {
                courseDoc.setName("redis完了");
                courseDoc.setIntro("redis多用来做缓存");
                courseDoc.setCourseTypeId(10086L);
            }
            courseDoc.setPrice(i + 666F);
            courseElasticsearchRepository.save(courseDoc);
        }
        System.out.println("保存成功");
    }

    /**
     *   通过id查询单条数据
     */
    @Test
    public void testFindById(){
        CourseDoc courseDoc = new CourseDoc();
        courseDoc.setId(1L);
        System.out.println(courseElasticsearchRepository.findById(courseDoc.getId()));
    }

    /**
     *     通过id删除
     */
    @Test
    public void testDeleteById(){
        CourseDoc courseDoc = new CourseDoc();
        courseDoc.setId(1L);
        courseElasticsearchRepository.deleteById(courseDoc.getId());
        System.out.println("删除成功");
    }


    /**
     *      DSL查询和DSL过滤
     *
     *  课程中的name包含  sql  模糊查询  match
     *  课程类型  -- 等值查询 term
     *  价格  price  -- 范围查询
     *      根据价格倒排序
     *  分页查询第二页   每页5条
     */
    @Test
    public void testSearch(){
        //==============================
        //构建查询
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        //===============查询条件===============
        //组合查询
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

        //模糊查询
        boolQueryBuilder.must(QueryBuilders.matchQuery("name","mysql"));

        List<QueryBuilder> filter = boolQueryBuilder.filter();
        //等值查询
        filter.add(QueryBuilders.termQuery("courseTypeId",10086L));

        //范围查询
        filter.add(QueryBuilders.rangeQuery("price").lte(680).gte(670));

        //添加查询条件
        nativeSearchQueryBuilder.withQuery(boolQueryBuilder);

        //分页  查询第二页，每页5条
        nativeSearchQueryBuilder.withPageable(PageRequest.of(1,6));

        //排序
        nativeSearchQueryBuilder.withSort(new FieldSortBuilder("price").order(SortOrder.DESC));


        //===============执行查询===============
        //根据builder构建查询对象
        SearchQuery searchQuery = nativeSearchQueryBuilder.build();
        //这个是执行查询
        Page<CourseDoc> page = courseElasticsearchRepository.search(searchQuery);


        //================返回结果==============
        //获取总条数
        long totalElements = page.getTotalElements();
        System.out.println("总条数:" + totalElements);

        //获取总页数
        int totalPages = page.getTotalPages();
        System.out.println("总页数:" + totalPages);

        //数据
        page.getContent().forEach(c->{
            System.out.println(c);
        });


    }




}